// pages/login/login.js
var app=getApp();
var config=require("../../api/config");
var util=require("../../utils/util");

Page({
  /*页面的初始数据*/
  data: {
    agree: true,
    pop_show: true,
    unionId: '',
    userinfo: '',
    user_auto: false,
    city_info: '',
    bind: '',
    parentId: null
  },
  /*生命周期函数--监听页面加载*/
  onLoad: function (options) {
    var that=this;
    if(options.parentId){
      that.setData({parentId:options.parentId})
    }else{
      if(wx.getStorageSync('parentId')){
        that.setData({parentId:wx.getStorageSync('parentId')})
      }
    }
    var city_info=wx.getStorageSync('city');
    that.setData({city_info:city_info})
    wx.getStorage({
      key: 'unionId',
      success: function(res){
        that.setData({unionId: res.data.unionId})
      },
    })
    // wx.getStorage({
    //   key: 'user_info',
    //   success: function(res){
    //     that.setData({user_auto: true,userinfo:res.data})
    //   },
    // })
  },
  // 立即体验
  nav_back:function(){
    wx.navigateBack({
      delta: 1,
      fail:function(){
        wx.switchTab({
          url: '/pages/home/home',
        })
      }
    });
  },
  // 协议
  nav_go:function(e){
    var index=e.currentTarget.dataset.index,title=e.currentTarget.dataset.title;
    wx.navigateTo({
      url: '../../mypage/webView/webView?title='+title+'&index='+index,
    })
  },
  // 授权用户信息
  getUserInfo:function(e){
    var that=this;
    if(e.detail){
      that.setData({userinfo:e.detail.userInfo})
      // 
      that.userinfo_decrypt_wx(e.detail)
    }
  },
  show_toast:function(){
    util.page_show_toast('请先勾选同意家巴啦《用户协议》和《隐私政策》',2000)
  },
  // 授权绑定手机
  getphonenumber:function(e){
    // console.log(e)
    var that=this,info=e.detail;
    if(info.encryptedData){
      that.phone_decrypt_wx(info)
    }else{
      wx.redirectTo({
        url: '../codeLogin/codeLogin?parentId='+that.data.parentId,
      })
    }
  },
  // 登录方式跳转
  nav_login:function(e){
    var index=e.currentTarget.dataset.index;
    if(index==1){
      wx.redirectTo({
        url: '../codeLogin/codeLogin',
      })
    }else{
      wx.redirectTo({
        url: '../passwordLogin/passwordLogin',
      })
    }
  },
  // 勾选
  change_agree:function(){
    this.setData({agree: !this.data.agree})
  },
  close_mask:function(){
    this.setData({pop_show: !this.data.pop_show})
  },
  // 头像信息解密
  userinfo_decrypt_wx:function(info){
    var that=this;
    var params={
      "openId": app.globalData.openId,
      "encryptedData": info.encryptedData,
      "iv": info.iv
    }
    config.decrypt_wx(params).then(res=>{
      if(res.data.code==200){
        var info=res.data.data;
        app.globalData.unionId=info.unionId;
        that.setData({unionId: info.unionId})
        wx.setStorageSync('unionId', info);
        wx.setStorageSync('user_info', info)
        //
        that.esti_bind_wx()
      }
    })
  },
  // 手机号解密
  phone_decrypt_wx:function(info){
    var that=this,bind=that.data.bind;
    var params={
      "openId": app.globalData.openId,
      "encryptedData": info.encryptedData,
      "iv": info.iv
    }
    config.decrypt_wx(params).then(res=>{
      if(res.data.code==200){
        var phone=res.data.data.phoneNumber;
        if(bind){
          that.user_bind_phone(phone)
        }else{
          that.user_bind_wx(phone)
        }
      }
    })
  },
  // 判断是否绑定微信
  esti_bind_wx:function(){
    var that=this;
    var params={
      "unionId": app.globalData.unionId,
      "openId": app.globalData.openId,
      "bindType": "1",
      "thirdAppId": app.globalData.appId
    };
    config.esti_bind_wx(params).then(res=>{
      if(res.data.code==200){
        var bind=res.data.data;
        if(bind){
          // 删除小程序及未解绑微信
          that.wx_login();
        }else{
          // 删除小程序及已解绑微信
          that.setData({user_auto:true})
        }
        that.setData({bind:bind})
      }else{
        util.page_show_toast('登录出错，请稍后再试',2000)
      }
    })
  },
  // 微信登录判断是否需要绑定手机号和获取token
  wx_login:function(){
    var that=this;
    var params={
      "unionId": app.globalData.unionId,
      "openId": app.globalData.openId,
      "bindType": "1",
      "thirdAppId": app.globalData.appId
    };
    config.wx_login(params).then(res=>{
      if(res.data.code==200){
        var info=res.data.data;
        if(info.userInfo.phone){
          util.page_show_toast('登录成功',1500);
          app.globalData.login=true;
          app.globalData.change_dom=true;
          app.globalData.change_table=true;
          wx.setStorageSync('userinfo', info.userInfo)
          wx.setStorageSync('token', info.token)
          wx.removeStorageSync('user_info')
          setTimeout(()=>{
            wx.navigateBack({
              delta: 1,
              fail:function(){
                wx.switchTab({
                  url: '/pages/home/home',
                })
              },
            });
          },1500)
        }else{
          that.setData({user_auto:true})
        }
      }else{
        util.page_show_toast('登录出错，请稍后再试',2000)
      }
    })
  },
  // 绑定手机
  user_bind_phone:function(phone){
    var that=this,unionId=that.data.unionId;
    var params={
      "phone": phone,
      "unionId": unionId,
    }
    config.wx_bind_phone(params).then(res=>{
      if(res.data.code==200){
        var bind=res.data.data;
        if(bind){
          that.wx_login();
        }else{
          util.page_show_toast('绑定出错，请稍后再试',2000)
        }
      }
    })
  },
  // 绑定手机号和微信
  user_bind_wx:function(phone){
    var that=this,userinfo=that.data.userinfo,city_info=that.data.city_info,unionId=that.data.unionId,parentId=that.data.parentId;
    var params={
      "nickName": userinfo.nickName,
      "phone": phone,
      "avatar": userinfo.avatarUrl,
      "sex": userinfo.gender,
      "unionId": unionId,
      "openId": app.globalData.openId,
      "bindType": "1",
      "thirdAppId": app.globalData.appId,
      "province": city_info?city_info.province:'',
      "city": city_info?city_info.city:'',
      "area": city_info?city_info.district:'',
      "town": city_info?city_info.town:'',
      "address": city_info?city_info.address:'',
      "parentId": parentId
    }
    if(!parentId){delete params.parentId}
    config.user_bind_wx(params).then(res=>{
      if(res.data.code==200){
        that.wx_login();
      }else{
        util.page_show_toast(res.data.message,1500)
      }
      // 事件统计
      app.td_app_sdk.event({
        id: 'register',
        label: '用户注册',
        params: {
          key1: util.formatTime(new Date()),
          key2: city_info.address,
          key3: userinfo.gender==1?'男':'女'
        }
      })
    })
  },
})